<template>
  <article>
    <el-form
      ref="form"
      label-width="120px"
      style="display: flex; flex-wrap: wrap"
    >
      <el-form-item label="报告时间:">
        <el-date-picker
          size="mini"
          v-model="form.reportDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          ref="performReportDate" @visible-change="isShowSelectOptions" @change="submitForm">
        </el-date-picker>
      </el-form-item>
      <el-form-item tyle="width: 280px" label="媒体:">
        <el-select
          id="id-creativerepost-componets-edit_table-toPlatformName"
          size="mini"
          v-model="form.platform"
          placeholder="请选择媒体"
          clearable
          ref="performPlatform" @visible-change="isShowSelectOptions">
          <el-option
            v-for="item in platformList"
            :key="item"
            :label="toPlatformName(item)"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item tyle="width: 280px" label="优化师:">
        <el-select
          id="id-creativerepost-componets-edit_table-operatorNameList"
          size="mini"
          v-model="form.operatorName"
          placeholder="请选择优化师"
          clearable
          filterable
          ref="performPlatform" @visible-change="isShowSelectOptions">
          <el-option
            v-for="item in operatorNameList"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item tyle="width: 280px" label="广告系列:">
        <el-input
          id="id-creativerepost-componets-edit_table-campaignName"
          placeholder="请输入广告系列名"
          v-model="form.campaignName"
          clearable
          size="mini">
        </el-input>
      </el-form-item>
      <el-form-item tyle="width: 280px" label="广告组名:">
        <el-input
          id="id-creativerepost-componets-edit_table-adsetName"
          placeholder="请输入广告组名"
          v-model="form.adsetName"
          clearable
          size="mini">
        </el-input>
      </el-form-item>
      <el-form-item tyle="width: 280px" label="广告名:">
        <el-input
          id="id-creativerepost-componets-edit_table-adName"
          placeholder="请输入广告名"
          v-model="form.adName"
          clearable
          size="mini">
        </el-input>
      </el-form-item>
      <el-form-item style="width: 280px">
        <el-button
          id="id-creativerepost-componets-edit_table-resetSearch"
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="submitForm">搜索</el-button>
        <el-button size="mini" icon="el-icon-delete" @click="resetSearch">清空</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row>分广告数据</el-row>-->
    <el-row style="padding-top: 1em">
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="filteredData"
        ref="crud"
        @on-load="onLoad"
        @sort-change="sortChange"
        :summary-method="summaryMethod"
      >
        <template slot-scope="{row}" slot="impressions">
          <div>{{thousandSeparator(row.impressions)}}</div>
        </template>
        <template slot-scope="{row}" slot="allExpend">
          <div>{{thousandSeparator(row.allExpend)}}</div>
        </template>
        <template slot-scope="{row}" slot="install">
          <div>{{thousandSeparator(row.install)}}</div>
        </template>
        <template slot-scope="{row}" slot="clicks">
          <div>{{thousandSeparator(row.clicks)}}</div>
        </template>
        <template slot-scope="{row}" slot="ctr">
          <div>{{row.ctr}}%</div>
        </template>
        <template slot-scope="{row}" slot="cvr">
          <div>{{row.cvr}}%</div>
        </template>
      </avue-crud>
    </el-row>
  </article>
</template>

<script>
  import {getCreativeAllPerformanceList} from "@/api/offer/creativeperformance";
  import Moment from 'moment'
  import {transformObjectList, findObject} from "@/util/util";
  import {getSysDictList} from "@/api/system/dict";

export default {

  name: "tags_table",
  props:{
    creativeId: String,
  },
  computed: {
    filteredData() {
      let list = [];
      if(this.data != null && this.data.length > 0) {
        this.data.forEach(row=>{
          if(this.form.platform != null && this.form.platform != '') {
            if(row.platform != this.form.platform) {
              return;
            }
          }
          if(this.form.operatorName != null && this.form.operatorName != '') {
            if(row.operatorName != this.form.operatorName) {
              return;
            }
          }
          if(this.form.adsetName != null && this.form.adsetName != '') {
            if(row.adsetName == null || row.adsetName.toLowerCase().indexOf(this.form.adsetName.toLowerCase()) == -1) {
              return;
            }
          }
          if(this.form.campaignName != null && this.form.campaignName != '') {
            if(row.campaignName == null || row.campaignName.toLowerCase().indexOf(this.form.campaignName.toLowerCase()) == -1) {
              return;
            }
          }
          if(this.form.adName != null && this.form.adName != '') {
            if(row.adNames == null || row.adNames.toLowerCase().indexOf(this.form.adName.toLowerCase()) == -1) {
              return;
            }
          }
          list.push(row);
        });
      }
      return list;
    },
  },
  data(){
    return{
      selectList: [],
      sortList: {
        name: '',
        orderBy: ''
      },
      isShowSelectOptions: true,
      platformList:[],
      platformDictList: [
        { value: 'facebook', label: 'Facebook' },
        { value: 'google', label: 'Google' },
        { value: 'bigo', label: 'Bigo' },
        { value: 'tiktok', label: 'TikTok' },
        { value: 'website', label: 'Website' },
      ],
      operatorNameList: [],
      form: {
        reportDate: [],
        platform: '',
        operatorName: null,
        adsetName: '',
        campaignName: '',
        adName: '',
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '过去三十天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(1, "months").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去十四天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(14, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去七天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(7, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      data:[],
      loading:false,
      option:{
        showSummary: true,
        menu:false,
        addBtn:false,
        column: [
          {
            label: "优化师",
            prop: "operatorName",
          },
          {
            label: "媒体",
            prop: "platform",
            dicData: [
              { value: 'facebook', label: 'Facebook' },
              { value: 'google', label: 'Google' },
              { value: 'bigo', label: 'Bigo' },
              { value: 'tiktok', label: 'TikTok' },
              { value: 'website', label: 'Website' },
            ],

          },
          {
            label: "广告账户id",
            prop: "accountId",
            hide: true,
          },
          {
            label: "广告系列名",
            prop: "campaignName",
            overHidden: true,
          },
          {
            label: "广告系列id",
            prop: "campaignId",
            overHidden: true,
            hide: true,
          },
          {
            label: "广告组名",
            prop: "adsetName",
            overHidden: true,
          },
          {
            label: "广告组id",
            prop: "adsetId",
            overHidden: true,
            hide: true,
          },
          {
            label: "广告名",
            prop: "adNames",
            overHidden: true,
          },
          {
            label: "广告id",
            prop: "adIds",
            overHidden: true,
            hide: true,
          },
          {
            label: "花费",
            prop: "allExpend",
            sortable: 'custom',
            formatter:(row) =>{
              return  row.allExpend.toLocaleString()
            }
          },
          {
            label: "曝光",
            prop: "impressions",
            sortable: 'custom',
            formatter:(row)=>{
              return  row.impressions.toLocaleString()
            }
          },
          {
            label: "点击",
            prop: "clicks",
            sortable: 'custom',
            formatter:(row)=>{
              return  row.clicks.toLocaleString()
            }
          },
          {
            label: "CTR",
            prop: "ctr",
            slot: true,
            sortable: 'custom',
            formatter:(row)=>{
              return  row.ctr.toLocaleString()
            }
          },
          {
            label: "安装",
            prop: "install",
            sortable: 'custom',
            formatter:(row)=>{
              return  row.install.toLocaleString()
            }
          },
          {
            label: "CVR",
            prop: "cvr",
            sortable: 'custom',
            formatter:(row)=>{
              return row.cvr.toLocaleString()
            }
          },
          {
            label: "安装成本",
            prop: 'installCost',
            sortable: 'custom',
          },
        ],
      }
    }
  },
  created() {
    getSysDictList('platforms').then(map=>{
      this.platformDictList = transformObjectList(map['platforms'],[
        {from: 'dictKey', to: 'value'},
        {from: 'dictValue', to: 'label'},
      ]);
      let column = findObject(this.option.column,'platform','prop');
      if(column != null) {
        column.dicData = this.platformDictList;
      }
    });
    this.onLoad();
  },
  methods:{
    summaryMethod({columns, data}) {
      const sums = [];
      let allExpendSum = 0;
      let impressionsSum = 0;
      let clicksSum = 0;
      let ctrSum = 0;
      let installSum = 0;
      let cvrSum = 0;
      let installCostSum = 0;
      if (data.length > 0) {
        data.forEach((row) => {
          allExpendSum += parseFloat(row.allExpend)
          impressionsSum += parseFloat(row.impressions)
          clicksSum += parseFloat(row.clicks)
          ctrSum += parseFloat(row.ctr)
          installSum += parseFloat(row.install)
          cvrSum += parseFloat(row.cvr)
          installCostSum += parseFloat(row.installCost)
        })
      }
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          if ([0].includes(index)) {
            sums[index] = '合计'
          } else if (column.label && column.label === "花费") {
            sums[index] = this.thousandSeparator(allExpendSum.toFixed(2))
          }else if (column.label && column.label === "曝光") {
            sums[index] = impressionsSum = this.thousandSeparator(impressionsSum.toFixed(2))
          }else if (column.label && column.label === "点击") {
            sums[index] = clicksSum = this.thousandSeparator(clicksSum.toFixed(2))
          }else if (column.label && column.label === "CTR") {
            sums[index] = ctrSum = this.thousandSeparator(ctrSum.toFixed(2))+ "%"
          }else if (column.label && column.label === "安装") {
            sums[index] = installSum = this.thousandSeparator(installSum.toFixed(2))
          }else if (column.label && column.label === "CVR") {
            sums[index] = cvrSum = this.thousandSeparator(cvrSum.toFixed(2)) + "%"
          }else if (column.label && column.label === "安装成本") {
            sums[index] = installCostSum = this.thousandSeparator(installCostSum.toFixed(2))
          } else {
            sums[index] = this.selectList.map(item => Number(item[column.property]));
          }
        });
      }
      return sums;
    },
    sortChange(val){
      let prop = val.prop
      if (val.order === "descending"){
        this.$refs.crud.data.sort((a,b) =>{
          return b[prop] - a[prop]
        })
      }else if (val.order === "ascending"){
        this.$refs.crud.data.sort((a,b) =>{
          return a[prop] - b[prop]
        })
      }else {
        this.resetSearch()
      }
    },
    thousandSeparator(num){
      let s = num.toString();
      let div = s.indexOf('.');
      let sign = (num < 0)?'-':'';
      let intPart = (div == -1)?s:s.substring(0,div);
      let dotPart = (div == -1)?'':s.substring(div);
      let finalIntPart = '';
      while(intPart.length > 3) {
        finalIntPart = ',' + intPart.substring(intPart.length - 3) + finalIntPart;
        intPart = intPart.substring(0,intPart.length-3);
      }
      return sign + intPart + finalIntPart + dotPart;
    },
    submitForm() {
      this.onLoad();
    },
    resetSearch() {
      this.form = {
        reportDate: [],
          platform: '',
          operatorName: null,
          adsetName: '',
          campaignName: '',
          adName: '',
      };
      this.onLoad();
    },
    toPlatformName(platform) {
      for(let i=0;i<this.platformDictList.length;i++) {
        if(this.platformDictList[i].value == platform) {
          return this.platformDictList[i].label;
        }
      }
      return platform;
    },
    onLoad(){
      this.loading = true;
      let query = {
        creativeId: this.creativeId,
      };
      if(this.form.reportDate != null && this.form.reportDate.length == 2) {
        query.beginDate = Moment(this.form.reportDate[0]).format('YYYY-MM-DD');
        query.endDate = Moment(this.form.reportDate[1]).format('YYYY-MM-DD');
      }
      getCreativeAllPerformanceList(
        Object.assign({}, query,{sortList: JSON.stringify(this.sortList)})
      ).then((res) => {
        this.data = res.data.data;
        let platformList = [];
        let operatorNameList = [];
        this.data.forEach(row=>{
          if(row.platform != null && row.platform != '' && !platformList.includes(row.platform)) {
            platformList.push(row.platform);
          }
          if(row.operatorName != null && row.operatorName != '' && !operatorNameList.includes(row.operatorName)) {
            operatorNameList.push(row.operatorName);
          }
        });
        this.platformList = platformList;
        this.operatorNameList = operatorNameList;
      }).finally(()=>{
        this.loading = false;
      });
    },
  }
}
</script>

<style scoped>

</style>
